package com.xbh.management.service;

import com.xbh.management.controller.UserController;
import com.xbh.management.entity.ManUserVO;
import com.xbh.management.entity.SecurityUserVO;
import com.xbh.management.model.ManMenu;
import com.xbh.management.model.ManUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: management-center
 * @description:
 * @author: 许宝华
 * @create: 2021-10-05 17:07
 */

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    private static Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    /**
     * 根据用户名查出用户详细信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("进入用户验证---->UserDetailsServiceImpl");
        //根据用户名查询
        ManUser user = userService.queryUser(username);
        log.info("查到的用户数据==="+user.toString());
        //判断用户信息
        if(user == null){
            log.info("用户不存在");
            throw new UsernameNotFoundException("用户不存在");
        }
        //查询当前用户所关联的所有菜单
        ManUserVO manUserVO = userService.queryUserRelationAllMenu(user);
        if(manUserVO==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<ManMenu> menuList = manUserVO.getMenuList();
        ArrayList<String> menuStringList = new ArrayList<>();
        for (ManMenu manMenu : menuList) {
            menuStringList.add(manMenu.toString());
        }
        SecurityUserVO securityUserVO = new SecurityUserVO();
        securityUserVO.setCurrentUserInfo(user);
        securityUserVO.setPermissionValueList(menuStringList);

        log.info("验证数据"+securityUserVO.toString());
        //校验账户状态属性是否正常，
        return securityUserVO;
    }
}
